import {Injectable, NgZone} from '@angular/core';

import {Platform,AlertController, LoadingController} from 'ionic-angular';

import {AppVersion} from '@ionic-native/app-version';
import {AppUpdate} from '@ionic-native/app-update';
import { FileTransfer, FileTransferObject} from '@ionic-native/file-transfer';
import { File } from '@ionic-native/file';
import { FileOpener } from '@ionic-native/file-opener';
import { Diagnostic } from '@ionic-native/diagnostic';

import {IntfService} from './intfService';
import { ParamService } from './paramService';
import {UrlService} from './urlService';
import {CommonUtilService} from "./commonUtilService";

@Injectable()
export class VersionService {

  targetPath: string = "/sdcard/Download/OutCallApp.apk"; //APP下载存放的路径，可以使用cordova file插件进行相关配置

   public localVersion:any;
  constructor(private platform: Platform,
              private alertCtrl: AlertController,
              private loadingCtrl: LoadingController,
              private intfService: IntfService,
              private appVersion: AppVersion,
              private appUpdate: AppUpdate,
              private transfer: FileTransfer,
              private file: File,
              private fileOpener: FileOpener,
              private diagnostic: Diagnostic,
              private commonUtil:CommonUtilService,
              //private androidPermissions: AndroidPermissions,
              private ngZone: NgZone) {
             console.log('Hello HttpService Provider');
  }

  //检查app最新版本并更新
  checkAndUpdateApp(){
    this.localVersion="1.0.0";
    //1.获取最新版本信息
    let verUrl = UrlService.updateUrl();
    this.intfService.getReq(verUrl, null, true).then(res1 => {

      console.log('new version:' + JSON.stringify(res1));
      ParamService.appConfig = res1.config; //进入登录页获取 wsl-xx.json 后获取的全局配置参数，先留存

      //2.获取本地当前版本信息
      this.appVersion.getVersionNumber().then((res2: string) => {
        console.log('getVersionNumber:' + res2);
        //3.如果版本不一致，则提示要升级
        // android 平台
        this.localVersion =res2;
        if(this.platform.is("android")){
          //处理手动更新问题,如果版本号一致，则提示已是最新版本.那就需要作区别，在登录时检查，和登录后检查
          if(res1.android.version == res2){
            if(ParamService.loginUser){
              this.commonUtil.showAlert({title:"消息提示",message:"您已获取最新版本"})
            }
          }
          if(res1.android.version != res2){
            //alert(res1.version + "|" + res2 + "|"+ res1.url);
            console.log(res1.android.version + "|" + res2 + "|"+ res1.android.url);
            this.updateConfirm(res1.android.version, res1.android.url);
          }
        }
        // ios 平台
        else if(this.platform.is("ios")){
          //处理手动更新问题,如果版本号一致，则提示已是最新版本.那就需要作区别，在登录时检查，和登录后检查
          if(res1.android.version == res2){
            if(ParamService.loginUser){
              this.commonUtil.showAlert({title:"消息提示",message:"您已获取最新版本"})
            }
          }
          if(res1.ios.version != res2){
            // alert(res1.ios.version + "|" + res2 + "|"+ res1.url);
            console.log(res1.ios.version + "|" + res2 + "|"+ res1.ios.url);
            this.updateConfirm(res1.ios.version, res1.ios.url);
          }
        }
        else{

        }
        //alert('23.');
      }).catch((error2) => {
        console.log('get local version error:' + error2.toString());
        // alert('2.' + error2.toString());
      });

    }).catch((error1) => {
      console.log('get new version error:' + error1.toString());
      //alert('1.' + error1.toString());
    });
  }

  //获取最新版本号
  getLatestVersion() {
    // let url = "/app/offline/queryLatestVersion";
    // let param = {"os": "android"};
    // this.httpService.postBody(this.updateUrl, param).then(res => {
    //   console.log('resp:' + JSON.stringify(res));
    //
    // });

    let reqUrl = UrlService.updateUrl();
    this.intfService.getReq(reqUrl, null, false).then(res => {
      console.log('resp:' + JSON.stringify(res));

    });
  }

  //获取本地app版本信息
  showUpdateConfirm() {
    // this.appVersion.getAppName();
    // this.appVersion.getPackageName();
    // this.appVersion.getVersionCode();
    // this.appVersion.getVersionNumber();
    this.appVersion.getVersionNumber().then((res: string) => {
      this.updateConfirm(res);
    }).catch((error) => {
      alert(error.toString());
    });
  }

  //检查app最新版本并更新，经测试appUpdate插件会闪退，原因没解决
  checkAndUpdateApp2(){
    this.appUpdate.checkAppUpdate(UrlService.updateUrl2()).then((res: string) => {
      //this.updateConfirm(res);
      alert("下载完成");
    }).catch((error) => {
      alert(error.toString());
    });
  }

  //弹出版本升级确认框
  updateConfirm(msg: string, apkUrl?: string){
    let confirm = this.alertCtrl.create({
      title: '版本更新',
      message: '发现最新版本' + msg + ',需要更新吗?',
      buttons: [
        {
          text: '取消',
          handler: () => {
            console.log('取消升级');
          }
        },
        {
          text: '更新',
          handler: () => {
            console.log('确定升级');
            //动态检查android存储权限 WRITE_EXTERNAL_STORAGE READ_EXTERNAL_STORAGE
            // this.androidPermissions.checkPermission(this.androidPermissions.PERMISSION.WRITE_EXTERNAL_STORAGE).then(
            //   (success) => {
            //     console.log('WRITE_EXTERNAL_STORAGE Permission granted');
            //     this.downloadAndOpen(apkUrl); //开始下载
            //   },
            //   (err) => {
            //     console.log('WRITE_EXTERNAL_STORAGE Permission not granted');
            //     this.androidPermissions.requestPermissions(this.androidPermissions.PERMISSION.WRITE_EXTERNAL_STORAGE);//申请权限
            //   }
            // );

            // this.diagnostic.isExternalStorageAuthorized().then((success) => {
            //   console.log('isExternalStorageAuthorized Permission granted');
            // }, (error) => {
            //
            // });
            // android 平台

            if(this.platform.is("android")){
              this.diagnostic.requestExternalStorageAuthorization().then( (status) => {
                console.log("external storage use was " + (status == this.diagnostic.permissionStatus.GRANTED ? "granted" : "denied"));
                if(status == this.diagnostic.permissionStatus.GRANTED){
                  this.downloadAndOpen(apkUrl); //开始下载
                }
              }, (error) => {

              });
            }
            // ios 平台
            else if(this.platform.is("ios")){
              window.open("itms-services://?action=download-manifest&url=https%3A%2F%2Fwww.pgyer.com%2Fapiv2%2Fapp%2Fplist%3FappKey%3Ddacae7ac4b8345aa87840d186abfef57%26_api_key%3D441ad932c32607fd128017371112cef4");
            }else{
              console.log("其他平台");
            }

            // this.diagnostic.requestExternalStorageAuthorization().then( (status) => {
            //   console.log("external storage use was " + (status == this.diagnostic.permissionStatus.GRANTED ? "granted" : "denied"));
            //   if(status == this.diagnostic.permissionStatus.GRANTED){
            //     this.downloadAndOpen(apkUrl); //开始下载
            //   }
            //   }, (error) => {
            //
            // });
          }
        }
      ]
    });
    confirm.present();
  }

  //下载apk并打开文件安装
  downloadAndOpen(apkUrl: string){
    //4.下载apk
    const fileTransfer: FileTransferObject = this.transfer.create();

    let downloading = this.loadingCtrl.create({
      content: "安装包正在下载...",
      dismissOnPageChange: false
    });

    downloading.present();

    fileTransfer.onProgress((event) => {
      // //方法1：进度，这里使用文字显示下载百分比,setTimeout也没法让数字变化
      // // setTimeout(function () {
      //   let downloadProgress = (event.loaded / event.total) * 100;
      //   downloading.setContent("已经下载：" + Math.floor(downloadProgress) + "%");
      //
      //   if (downloadProgress > 99) {
      //     downloading.dismiss();
      //   }
      //
      // // },1000);

      /* setTimeout(() => {
       uploading.dismiss();
       }, 10000);*/

      //方法2：进度条数字会动态变化，但测试发现安卓7.0会报错
      this.ngZone.run(() => {
        if (event.lengthComputable) {
          let downloadProgress = event.loaded / event.total * 100;
          if (downloadProgress > 99) {
            downloading.dismiss();
          }
          downloading.setContent("已经下载：" + Math.floor(downloadProgress) + "%");

        }
      });

    });

    fileTransfer.download(apkUrl, this.targetPath, true).then((entry) => {
      console.log('下载完成: ' + entry.toURL());
      //5.下载完成后自动打开文件安装
      this.fileOpener.open(this.targetPath, 'application/vnd.android.package-archive').then(
        ()=>{
        }).catch((error5) => {
        alert('5.' + JSON.stringify(error5));
      });
    }).catch((error4) => {
      alert('4.' + JSON.stringify(error4));
    });
  }

  //获取本地版本号
  getLocalVersion(){
    //获取本地当前版本信息
    // return this.appVersion.getVersionNumber().then((res2: string) => {
    //   return res2;
    // }).catch((error2) => {
    //   console.log('get local version error:' + error2.toString());
    //   //alert('2.' + error2.toString());
    // });
    return this.appVersion.getVersionNumber();
  }

}
